<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\LogRefund;

/**
 * LogRefundSearch represents the model behind the search form about `backend\models\LogRefund`.
 */
class LogRefundSearch extends LogRefund
{
    /**
     * @inheritdoc
     */
	public $username;
	public $start_time;
	public $end_time;
    public function rules()
    {
        return [
            [['refund_id',  'uid', 'starttime', 'endtime',  'state_count', 'state'], 'integer'],
            [['refund_no', 'third_refund_no', 'zfb_batch_no', 'done_list', 'transaction_id', 'trade_no', 'memo_xml'], 'safe'],
            [['username'], 'string', 'max' => 10],
            [['start_time','end_time'],'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $condition=" pay_trade.trade_class=1  and log_refund.type_class=0";
        //如果运营商，加上地址过滤
        $user_type = Yii::$app->user->identity->user_type;
        $user_id=Yii::$app->user->identity->user_id;
        if ($user_type != 1)
        {//非后台管理员
            if(intval($user_id)>0){
                $ifxgt=OperatorRelation::getifXat();//香港 澳门 台湾   直接in('台湾省','香港特别行政区','澳门特别行政区')
                $ifhascity=OperatorRelation::ifhascity();
                $ifhaszxsCountry=OperatorRelation::ifhaszxsCountry();
                $ifhascountry=OperatorRelation::ifhascountry();
                $ifhasprovince=OperatorRelation::ifhasprovince();
                if($ifhasprovince){
                    $provinceStr=OperatorRelation::getProvinceNameById();
                    $condition.=" and SUBSTR(SUBSTRING_INDEX(pay_trade.address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',1))+1) in ({$provinceStr})";
                }
                if($ifhascity){
                    $cityStr=OperatorRelation::getCityNameByIdNprovincename();
                    if($ifhasprovince){
                        $condition.=" or SUBSTR(SUBSTRING_INDEX(pay_trade.address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',1))+1) in ({$cityStr})";
                    }else{
                        $condition.=" and SUBSTR(SUBSTRING_INDEX(pay_trade.address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',1))+1) in ({$cityStr})";
                    }
                }
                if($ifhaszxsCountry||$ifhascountry){
                    if($ifhasprovince||$ifhascity){
                        $a="or";
                    }else{
                        $a="and";
                    }
                    $countryStr=OperatorRelation::getcountryNameById();
                    if($ifhaszxsCountry){//有直辖市 也有区县 合并条件
                        if($ifhascountry){
                            //$condition.=$a."  (SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$countryStr}) or SUBSTR(SUBSTRING_INDEX(address,' ',3),CHAR_LENGTH( SUBSTRING_INDEX(address,' ',2))+1) in ({$countryStr}))";
                            $condition.=$a."  (SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',2))) in ({$countryStr}) or SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',3))) in ({$countryStr}))";
                        }else{
                            //$condition.=$a."  SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$countryStr}) ";
                            $condition.=$a."  SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',2))) in ({$countryStr}) ";
                        }
                    }else{
                        if($ifhascountry){
                            //  $condition.=$a."  SUBSTR(SUBSTRING_INDEX(address,' ',3),CHAR_LENGTH( SUBSTRING_INDEX(address,' ',2))+1) in ({$countryStr})";
                            $condition.=$a."  SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',3))) in ({$countryStr})";
                        }
                    }
                }
            }
            
        }
        $query = LogRefund::find()->joinWith(['payTradeInfo'])->joinWith(['userInfo'])->where($condition);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'refund_id' => $this->refund_id,
        //    'doing' => $this->doing,
            'uid' => $this->uid,
        //    'type' => $this->type,
            'starttime' => $this->starttime,
            'endtime' => $this->endtime,
           'state' => $this->state,
            'state_count' => $this->state_count,
        ]);

        $query->andFilterWhere(['like', 'refund_no', $this->refund_no])
            ->andFilterWhere(['like', 'third_refund_no', $this->third_refund_no])
            ->andFilterWhere(['like', 'zfb_batch_no', $this->zfb_batch_no])
            ->andFilterWhere(['like', 'done_list', $this->done_list])
            ->andFilterWhere(['like', 'transaction_id', $this->transaction_id])
            ->andFilterWhere(['like', 'log_refund.trade_no', $this->trade_no])
            ->andFilterWhere(['like', 'memo_xml', $this->memo_xml])
        	->andFilterWhere(['like', 'user_info.username', $this->username]);

        return $dataProvider;
    }
    /*报表的搜索 */
    public function reportSearch($params)
    {
        $condition=" pay_trade.trade_class=1 ";
        //如果运营商，加上地址过滤
        $user_type = Yii::$app->user->identity->user_type;
        $user_id=Yii::$app->user->identity->user_id;
        if ($user_type != 1)
        {//非后台管理员
            if(intval($user_id)>0){
                $ifxgt=OperatorRelation::getifXat();//香港 澳门 台湾   直接in('台湾省','香港特别行政区','澳门特别行政区')
                $ifhascity=OperatorRelation::ifhascity();
                $ifhaszxsCountry=OperatorRelation::ifhaszxsCountry();
                $ifhascountry=OperatorRelation::ifhascountry();
                $ifhasprovince=OperatorRelation::ifhasprovince();
                if($ifhasprovince){
                    $provinceStr=OperatorRelation::getProvinceNameById();
                    $condition.=" and SUBSTR(SUBSTRING_INDEX(pay_trade.address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',1))+1) in ({$provinceStr})";
                }
                if($ifhascity){
                    $cityStr=OperatorRelation::getCityNameByIdNprovincename();
                    if($ifhasprovince){
                        $condition.=" or SUBSTR(SUBSTRING_INDEX(pay_trade.address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',1))+1) in ({$cityStr})";
                    }else{
                        $condition.=" and SUBSTR(SUBSTRING_INDEX(pay_trade.address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',1))+1) in ({$cityStr})";
                    }
                }
                if($ifhaszxsCountry||$ifhascountry){
                    if($ifhasprovince||$ifhascity){
                        $a="or";
                    }else{
                        $a="and";
                    }
                    $countryStr=OperatorRelation::getcountryNameById();
                    if($ifhaszxsCountry){//有直辖市 也有区县 合并条件
                        if($ifhascountry){
                            //$condition.=$a."  (SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$countryStr}) or SUBSTR(SUBSTRING_INDEX(address,' ',3),CHAR_LENGTH( SUBSTRING_INDEX(address,' ',2))+1) in ({$countryStr}))";
                            $condition.=$a."  (SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',2))) in ({$countryStr}) or SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',3))) in ({$countryStr}))";
                        }else{
                            //$condition.=$a."  SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$countryStr}) ";
                            $condition.=$a."  SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',2))) in ({$countryStr}) ";
                        }
                    }else{
                        if($ifhascountry){
                            //  $condition.=$a."  SUBSTR(SUBSTRING_INDEX(address,' ',3),CHAR_LENGTH( SUBSTRING_INDEX(address,' ',2))+1) in ({$countryStr})";
                            $condition.=$a."  SUBSTR(pay_trade.address,1,CHAR_LENGTH(SUBSTRING_INDEX(pay_trade.address,' ',3))) in ({$countryStr})";
                        }
                    }
                }
            }
            
        } 
        $query = LogRefund::find()->joinWith(['payTradeInfo'])->joinWith(['userInfo'])->where($condition);
    	$dataProvider = new ActiveDataProvider([
    			'query' => $query,
    			'sort'  => [
    				'defaultOrder' => ['addtime' =>SORT_DESC]
    			]
    	]);
    
    	$this->load($params);
    	$query->andFilterWhere([
    			'refund_id' => $this->refund_id,
    			//    'doing' => $this->doing,
    			'uid' => $this->uid,
    			//    'type' => $this->type,
    			'starttime' => $this->starttime,
    			'endtime' => $this->endtime,
    			'state' => $this->state,
    			'state_count' => $this->state_count,
    			]);
    
    	$query->andFilterWhere(['like', 'refund_no', $this->refund_no])
    	->andFilterWhere(['like', 'third_refund_no', $this->third_refund_no])
    	->andFilterWhere(['like', 'zfb_batch_no', $this->zfb_batch_no])
    	->andFilterWhere(['like', 'done_list', $this->done_list])
    	->andFilterWhere(['like', 'transaction_id', $this->transaction_id])
    	->andFilterWhere(['like', 'trade_no', $this->trade_no])
    	->andFilterWhere(['like', 'memo_xml', $this->memo_xml])
    	->andFilterWhere(['like', 'user_info.username', $this->username]);
    	
    	if($this->start_time)
    		$query->andFilterWhere(['>=', 'pay_trade.refund_time', strtotime($this->start_time)]);
    	if($this->end_time)
    		$query->andFilterWhere(['<', 'pay_trade.refund_time', strtotime("{$this->end_time} + 1 day")]);
    	
    	$row = LogRefund::find()->select(['refund_amount'=>'SUM(`rmb`)'])->joinWith(['payTradeInfo'])
    	                       ->where($condition)
						    	->andFilterWhere(['>=','pay_trade.refund_time',strtotime($this->start_time)])
						    	->andFilterWhere(['<','pay_trade.refund_time',strtotime("{$this->end_time} + 1 day")])
						    	->andFilterWhere(['=','state',$this->state])	
						    	->andFilterWhere(['=','trade_class',1])	
    							->one();
    					
    	return array('dataProvider'=>$dataProvider,'refund_amount'=>$row->refund_amount?$row->refund_amount:'0.00');
    }
}
